package middleware

import (
	"p2p-server/pkg/database"
	"p2p-server/pkg/util"
	"strconv"

	"github.com/gogf/gf/v2/net/ghttp"
)

// AuthMiddleware 鉴权中间件
func AuthMiddleware(r *ghttp.Request) {
	// 跳过非WebSocket请求的鉴权
	if r.URL.Path != "/ws" {
		r.Middleware.Next()
		return
	}

	// 获取请求参数
	roomID := r.GetQuery("roomId").String()
	userIDStr := r.GetQuery("userId").String()
	userTypeStr := r.GetQuery("userType").String() // customer 或 provider

	// 参数验证
	if roomID == "" || userIDStr == "" || userTypeStr == "" {
		util.Errorf("鉴权失败：缺少必要参数 roomId=%s, userId=%s, userType=%s", roomID, userIDStr, userTypeStr)
		r.Response.WriteStatus(401, "Unauthorized: Missing required parameters")
		return
	}

	// 转换用户ID为uint64
	userID, err := strconv.ParseUint(userIDStr, 10, 64)
	if err != nil {
		util.Errorf("鉴权失败：用户ID格式错误 %v", err)
		r.Response.WriteStatus(400, "Bad Request: Invalid user ID format")
		return
	}

	// 确定用户类型
	isCustomer := userTypeStr == "customer"
	if userTypeStr != "customer" && userTypeStr != "provider" {
		util.Errorf("鉴权失败：用户类型错误 userType=%s", userTypeStr)
		r.Response.WriteStatus(400, "Bad Request: Invalid user type")
		return
	}

	// 验证会话有效性
	valid, err := database.IsValidSession(roomID, userID, isCustomer)
	if err != nil {
		util.Errorf("鉴权失败：验证会话出错 %v", err)
		r.Response.WriteStatus(500, "Internal Server Error")
		return
	}

	if !valid {
		util.Errorf("鉴权失败：无效的会话 roomId=%s, userId=%s, userType=%s", roomID, userIDStr, userTypeStr)
		r.Response.WriteStatus(401, "Unauthorized: Invalid session")
		return
	}

	// 鉴权通过，继续处理请求
	util.Infof("鉴权成功：%s用户 %s 进入房间 %s", userTypeStr, userIDStr, roomID)
	
	// 将用户信息存储到请求上下文中，供后续处理使用
	r.SetParam("roomId", roomID)
	r.SetParam("userId", userID)
	r.SetParam("userType", userTypeStr)
	
	r.Middleware.Next()
}